<template>
  <div>
    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20" class="topBar">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="clearInput"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="searchNotice"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="16">
          <el-button
            type="primary"
            @click="showAddDialog"
            style="float: right"
            >添加公告</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="types" style="width: 100%" :header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }" border>
        <!-- 表格区 -->
        <el-table-column label="id" prop="id" width="80px"> </el-table-column>
        <el-table-column label="大屏图片" prop="picture">
          <template #default="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.picture"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="公告内容" prop="content"> </el-table-column>
        <!-- 操作区域 -->
        <el-table-column label="操作" width="130px">
          <template #default="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editType(scope.row)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row.id)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="50%"
      :before-close="handleClose">
      <el-form
        :model="noticesForm"
        :rules="noticesFormRules"
        ref="noticesFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="公告内容" prop="content">
          <el-input v-model="noticesForm.content"></el-input>
        </el-form-item>
        <el-form-item label="上传封面图片">
          <el-upload
            class="upload-demo"
            action="http://112.74.61.241:8081/minio/upload"
            :limit="1"
            :on-remove="addAfficheRemove"
            :on-success="addAfficheSuccess"
            :file-list="addAfficheList"
            list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="el-upload__tip">
                只能上传一张jpg/png文件，且不超过500kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import { getNotices, addNotices, editNotices, delNotices, searchNotices } from '@/api/Notice/index'
import { addLogs } from '#/Home/Home'
import { reactive, toRefs } from 'vue-demi';
import { ElMessage, ElMessageBox } from 'element-plus'
export default {
  setup() {
    const state = reactive({
      queryInfo: {
        query: "",
        pageNum: 1,
        pageSize: 5,
      },
      types: [],
      dialogTitle: '添加公告', // 对话框标题
      dialogVisible: false,
      noticesForm: {
        content: '',
        picture: ''
      },
      addAfficheList: new Array(0),
      editFlag: false,
      // 统计课程分类的总数量
      total: 0,
      noticesFormRules: {
        content: [
          { required: true, message: "请输入公告内容", trigger: "blur" },
        ],
      }
    })
    
    // 获取所有课程
    const getInfo = async() => {
      await getNotices(state.queryInfo.pageNum, state.queryInfo.pageSize).then(res => {
        const result:any = res.data
        if(result.ret === 0) {
          state.types = result.orgs.nots.content;
          state.total = result.orgs.nots.totalElements
        } else {
          ElMessage.error('服务器请求错误！');
        }
        state.noticesForm = {
          content: '',
          picture: ''
        }
        state.addAfficheList = []
      })
    }
    const showAddDialog = () => {
      state.dialogTitle = '添加公告'
      state.editFlag = false;
      state.noticesForm = {
        content: '',
        picture: ''
      }
      state.addAfficheList = []
      state.dialogVisible = true;
    }
    const handleClose = (done) => {
      ElMessageBox.confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {});
    }
    const addAfficheSuccess = (res) => {
      state.noticesForm.picture = res.url;
    }
    const addAfficheRemove = (res) => {

    }
    const submit = async() => {
      if(!state.noticesForm.content) {
        return ElMessage.error('请输入公告名称！');
      }
      if(state.editFlag) {
        await editNotices(state.editFlag, state.noticesForm).then(async res => {
          if(res.status === 200) {
           ElMessage.success('修改公告成功！');
            state.dialogVisible = false;
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '修改了公告',
            })
            getInfo();
          } else {
            ElMessage.error('修改公告出错！');
          }
        })
      } else {
        await addNotices(state.noticesForm).then(async res => {
          if(res.status === 200) {
            ElMessage.success('添加公告成功！');
            state.dialogVisible = false;
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '添加了新公告',
            })
            getInfo();
          } else {
            ElMessage.error('添加公告出错！');
          }
        })
      }
    }
    // 搜索课程
    const searchNotice = async() => {
      if(!state.queryInfo.query) {
        return ElMessage.error('请输入名称')
      }
      state.queryInfo.pageNum = 1;
      await searchNotices(state.queryInfo).then(async (res:any) => {
        if(res.status === 200) {
          state.types = res.data.orgs.nots.content
          state.total = res.data.orgs.nots.totalElements
          if(state.types === []) {
            ElMessage.info('搜索结果为空')
          } else {
            ElMessage.success('搜索成功！')
          }
        } else {
          ElMessage.error(res.data.msg)
        }
      })
    }
    // 清除输入框的内容
    const clearInput = () => {
      state.queryInfo.pageNum = 1;
      state.queryInfo.pageSize = 5;
      getInfo();
    }
    // 打开编辑课程对话框
    const editType = (row:any) => {
      type picObj = {
        name?: string,
        url?: string
      }
      const obj:picObj = {
        name: '大屏图片',
        url: row.picture
      };
      state.addAfficheList = [obj];
      state.editFlag = row.id;
      state.noticesForm = row;
      state.dialogTitle = '修改公告';
      state.dialogVisible = true;
    }
    // 删除课程
    const removeById = async(id) => {
      const confirmResult = await ElMessageBox.confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if(confirmResult === 'confirm') {
        await delNotices(id).then(async (res: any) => {
          if(res.status === 200) {
            ElMessage.success('成功删除该公告！')
            await addLogs({
              userId: window.sessionStorage.getItem('userId'),
              behavior: '删除了公告',
            })
            getInfo()
          } else {
            ElMessage.error(res.data.msg)
          }
        })
      }
    }
    // 每页的条目数改变
    const handleSizeChange = (newSize: number) => {
      state.queryInfo.pageSize = newSize
      getInfo();
    }
    // 页码改变
    const handleCurrentChange = (newPage: number) => {
      state.queryInfo.pageNum = newPage
      getInfo();
    }
    getInfo()
    return {
      ...toRefs(state),
      getInfo,
      showAddDialog,
      handleClose,
      addAfficheSuccess,
      addAfficheRemove,
      submit,
      searchNotice,
      clearInput,
      editType,
      removeById,
      handleSizeChange,
      handleCurrentChange
    };
  },
};
</script>

<style lang='scss' scoped>
.topBar {
  margin-bottom: 20px;
}
</style>